//
//  BCClipGridLayer.m
//  图片编辑
//
//  Created by aaaa on 2020/3/27.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCClipGridLayer.h"
#import <UIKit/UIKit.h>

static const CGFloat InnerLineWidth  = 1.0;
static const CGFloat BorderLineWidth = 1.5;
static const CGFloat CornerLineWidth = 2.0;

//遮罩层
@interface BCGridMaskLayer : CAShapeLayer

@end
@implementation BCGridMaskLayer
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super init];
    if (self) {
        self.frame = frame;
        [self setFillRule:kCAFillRuleEvenOdd];
        [self setFillColor:[[UIColor colorWithWhite:0 alpha:0.4] CGColor]];
    }
    return self;
}

//重新设置遮罩路径
-(void)setGridRect:(CGRect)gridRect{
    CGMutablePathRef path =CGPathCreateMutable();
    CGRect cropRect = gridRect;
    CGPathAddRect(path, nil, self.bounds);
    CGPathAddRect(path, nil, cropRect);
    self.path = path;
}

@end

@interface BCClipGridLayer ()
@property (nonatomic, strong) BCGridMaskLayer *maskLayer;
@property (nonatomic, assign) CGRect gridRect;
@end

@implementation BCClipGridLayer
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super init];
    if (self) {
        
        self.frame       = frame;
        self.lineWidth   = BorderLineWidth;
        self.fillColor   = [UIColor clearColor].CGColor;
        self.strokeColor = [UIColor whiteColor].CGColor;
        
        _maskLayer = [[BCGridMaskLayer alloc]initWithFrame:self.bounds];
        [self addSublayer:_maskLayer];
    }
    return self;
}

//设置遮罩范围 并重新绘制网格
-(void)setGridRect:(CGRect)gridRect
           animate:(BOOL)animate
{
    _gridRect = gridRect;
//    [UIView animateWithDuration:animate ? 1 : 0 animations:^{
        [_maskLayer setGridRect:gridRect];
        [self drawGridBorderAndLine];
//    }];
}

//画网格
-(void)drawGridBorderAndLine{
    if (CGRectEqualToRect(_gridRect, CGRectZero)) {
        return;
    }
    
    UIBezierPath *path = [[UIBezierPath alloc] init];
    path.lineWidth = InnerLineWidth;
    CGFloat distance = 0;
    for(int i=0;i<4;++i){ /** 竖线 */
        [path moveToPoint:CGPointMake(_gridRect.origin.x+distance, _gridRect.origin.y)];
        [path addLineToPoint:CGPointMake(_gridRect.origin.x+distance, _gridRect.origin.y+_gridRect.size.height)];
        distance += _gridRect.size.width/3;
    }
    distance = 0;
    for(int i=0;i<4;++i){ /** 横线 */
        [path moveToPoint:CGPointMake(_gridRect.origin.x, _gridRect.origin.y+distance)];
        [path addLineToPoint:CGPointMake(_gridRect.origin.x+_gridRect.size.width, _gridRect.origin.y+distance)];
        distance += _gridRect.size.height/3;
    }
    self.path = path.CGPath;
}

@end
